package com.like.lazyfragment

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import com.like.lazyfragment.ui3.Fragment1
import com.like.lazyfragment.ui3.Fragment2
import com.like.lazyfragment.ui3.Fragment3
import kotlinx.android.synthetic.main.activity_main2.*
import androidx.fragment.app.FragmentManager as FragmentManager1

/**
 * 懒加载实现方案1  通过Lifecyler实现
 */
class Main3Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        val arrayListOf = arrayListOf<Fragment>()
        arrayListOf.add(Fragment1())
        arrayListOf.add(Fragment2())
        arrayListOf.add(Fragment3())
//        arrayListOf.add(Fragment4())
//        arrayListOf.add(Fragment5())
        val myAdapter = MyAdapter(arrayListOf, supportFragmentManager)


        viewPager.adapter = myAdapter;
//        viewPager.offscreenPageLimit=arrayListOf.size;

        tabLayout.setupWithViewPager(viewPager)

    }

    /**
     * BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT  ////设置成这样，
     * 每次fragmant里面 就只会走onpause和onresume方法了。
     * 可见进走onresume,不可见时走onpause
     */
    class MyAdapter(var fragments: ArrayList<Fragment>, fm: FragmentManager1) :
        FragmentPagerAdapter(
            fm,
            //FragmentStatePagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT, 兼容以前那种方式实现的懒加载
            BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
        private val arrayOf = arrayOf(
            "第一页",
            "第二页",
            "第三页"
        )

        override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
            super.setPrimaryItem(container, position, `object`)
        }

        override fun getItem(position: Int): Fragment {
            return fragments[position]
        }

        override fun getCount(): Int {
            return arrayOf.size;
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return arrayOf[position]
        }
    }

}
